package main

import (
	"context"
	"example/gorm-gen/dao"
	"example/gorm-gen/model"
	"fmt"
	"log"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	// 初始化数据库连接
	db := getDb()

	// 初始化 DAO
	dao.SetDefault(db)

	// 示例：增删改查操作
	ctx := context.Background()

	// 1. 插入数据
	newUser := &model.LabUser{
		Name:       "John Doe",
		LoginName:  "johndoe",
		Passworld:  "password123",
		Age:        30,
		CreateTime: time.Now(),
		CreateID:   1,
		UpdateTime: time.Now(),
		UpdateID:   1,
	}
	err := dao.LabUser.WithContext(ctx).Create(newUser)
	if err != nil {
		log.Fatalf("Failed to create user: %v", err)
	}
	fmt.Printf("Inserted User ID: %d\n", newUser.ID)

	newUser2 := &model.LabUser{
		Name:       "John Doe2",
		LoginName:  "johndoe2",
		Passworld:  "password123",
		Age:        30,
		CreateTime: time.Now(),
		CreateID:   1,
		UpdateTime: time.Now(),
		UpdateID:   1,
	}

	err = dao.LabUser.WithContext(ctx).Create(newUser2)
	if err != nil {
		log.Fatalf("Failed to create user: %v", err)
	}
	fmt.Printf("Inserted User ID: %d\n", newUser2.ID)

	// 2. 查询数据
	user, err := dao.LabUser.WithContext(ctx).Where(dao.LabUser.ID.Eq(newUser.ID)).First()
	if err != nil {
		log.Fatalf("Failed to fetch user: %v", err)
	}
	fmt.Printf("Fetched User: %+v\n", user)

	// 3. 更新数据
	_, err = dao.LabUser.WithContext(ctx).Where(dao.LabUser.ID.Eq(newUser.ID)).Updates(map[string]interface{}{
		"Name":       "John Updated",
		"UpdateID":   2,
		"UpdateTime": time.Now(),
	})
	if err != nil {
		log.Fatalf("Failed to update user: %v", err)
	}
	fmt.Println("User updated successfully")

	// 4. 删除数据
	_, err = dao.LabUser.WithContext(ctx).Where(dao.LabUser.ID.Eq(newUser.ID)).Delete()
	if err != nil {
		log.Fatalf("Failed to delete user: %v", err)
	}
	fmt.Println("User deleted successfully")
}

func getDb() *gorm.DB {
	// 数据库连接信息
	dsn := "host=localhost user=lab password=1234qwer dbname=go-test port=5436 sslmode=disable TimeZone=Asia/Shanghai"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	return db
}
